<template>
  <div>
    <el-form>
      <el-row>
        <table style="width: 98%" class="tab-table">
          <tr>
            <th scope="col" width="30%" align="left">
              <label>{{ $t("business.workload.resource") }}</label>
            </th>
            <th scope="col" width="30%" align="left">
              <label>{{ $t("business.workload.limit") }}</label>
            </th>
            <th align="left" />
          </tr>
          <tr v-for="(row, index) in hards" v-bind:key="index">
            <td>
              <ko-data-item
                v-model="row.key"
                item-ype="flatSelect"
                :selections="resourceList"
                @change="onSourceTypeChange"
              />
            </td>
            <td v-if="unitSuffixDesc(row) !== 'none'">
              <ko-data-item
                v-model="row.value"
                :dividerName="unitSuffixDesc(row)"
                itemType="number"
              />
            </td>
            <td v-else>
              <ko-data-item v-model="row.value" itemType="input" />
            </td>
            <td>
              <el-button
                type="text"
                style="font-size: 10px"
                @click="onDeleteHard(index)"
              >
                {{ $t("commons.button.delete") }}
              </el-button>
            </td>
          </tr>
          <tr>
            <td align="left">
              <el-button @click="onAddHard">{{
                $t("commons.button.add")
              }}</el-button>
            </td>
          </tr>
        </table>
      </el-row>

      <div v-if="hasSelector">
        <h4 style="float: left; margin-top: 20px">Quota Scopes</h4>
        <el-tooltip class="item" effect="dark" placement="bottom">
          <i
            style="margin-top: 20px; margin-left: 7px"
            class="el-icon-question"
          />
          <template v-slot:content>
            <div>
              <div>
                <span>{{
                  $t("business.configuration.best_effort", ["BestEffort"])
                }}</span>
              </div>
              <ul>
                pods
              </ul>
              <div>
                <span>{{
                  $t("business.configuration.best_effort", [
                    "Terminating, NotTerminating, NotBestEffort and PriorityClass"
                  ])
                }}</span>
              </div>
              <ul>
                pods
              </ul>
              <ul>
                cpu
              </ul>
              <ul>
                memory
              </ul>
              <ul>
                requests.cpu
              </ul>
              <ul>
                requests.memory
              </ul>
              <ul>
                limits.cpu
              </ul>
              <ul>
                limits.memory
              </ul>
            </div>
          </template>
        </el-tooltip>
      </div>

      <el-row v-if="hasSelector">
        <table style="width: 98%" class="tab-table">
          <tr>
            <th scope="col" width="30%" align="left">
              <label>ScopeName</label>
            </th>
            <th scope="col" width="30%" align="left">
              <label>Operator</label>
            </th>
            <th scope="col" width="30%" align="left"><label>Values</label></th>
            <th align="left" />
          </tr>
          <tr v-for="(row, index) in selectors" v-bind:key="index">
            <td>
              <ko-data-item
                v-model="row.scopeName"
                itemType="select"
                :selections="scopeList"
                @change="onScopeNameChange(row)"
              />
            </td>
            <td>
              <ko-data-item
                v-model="row.operator"
                item-ype="flatSelect"
                :disabled="isOperatorOnlyExist(row.scopeName)"
                :selections="operatorList"
                @change="row.values = ''"
              />
            </td>
            <td>
              <ko-data-item
                v-model="row.values"
                :disabled="
                  row.operator === 'Exists' || row.operator === 'DoesNotExist'
                "
                :placeholder="$t('business.configuration.split_help')"
                itemType="input"
              />
            </td>
            <td>
              <el-button
                type="text"
                style="font-size: 10px"
                @click="onDeleteScope(index)"
              >
                {{ $t("commons.button.delete") }}
              </el-button>
            </td>
          </tr>
          <tr>
            <td align="left">
              <el-button @click="onAddScope">
                {{ $t("commons.button.add") }}
              </el-button>
            </td>
          </tr>
        </table>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import {
  cpuUnitConvert,
  memoryUnitConvert
} from "@/views/domain/kubeHud/utils/unitConvert";
import { ref, watch } from "vue";
import { ResourceQuota, ResourceQuotaSpec } from "../../../api/k8s";

type Prop = {
  resourceQuotaObj: ResourceQuotaSpec;
  hasSelector?: boolean;
};

const props = defineProps<Prop>();

const hards = ref<any[]>([]);
const all_resource_list = [
  "limits.cpu",
  "limits.memory",
  "requests.cpu",
  "requests.memory",
  "configmaps",
  "pods",
  "replicationcontrollers",
  "resourcequotas",
  "services",
  "services.loadbalancers",
  "services.nodeports",
  "secrets",
  "requests.storage",
  "persistentvolumeclaims"
];
const resourceList = ref<string[]>([]);
const selectors = ref<any[]>([]);
const operatorList = ["In", "NotIn", "Exists", "DoesNotExist"];
const scopeList = [
  {
    label: "Terminating (.spec.activeDeadlineSeconds >= 0)",
    value: "Terminating"
  },
  {
    label: "NotTerminating (.spec.activeDeadlineSeconds is nil)",
    value: "NotTerminating"
  },
  {
    label: "BestEffort (have best effort quality of service)",
    value: "BestEffort"
  },
  {
    label: "NotBestEffort (not have best effort quality of service)",
    value: "NotBestEffort"
  },
  {
    label: "PriorityClass (references the specified priority class)",
    value: "PriorityClass"
  }
];

const onAddHard = () => {
  hards.value.push({ key: "", value: "" });
};

const onDeleteHard = (index: number) => {
  hards.value.splice(index, 1);
};

const onAddScope = () => {
  selectors.value.push({
    scopeName: "",
    operator: "",
    values: ""
  });
};

const onDeleteScope = (index: number) => {
  selectors.value.splice(index, 1);
};

const onSourceTypeChange = () => {
  resourceList.value = all_resource_list.filter(src => {
    return hards.value.findIndex(hard => hard.key === src) === -1;
  });
};

const isOperatorOnlyExist = scopeName => {
  return (
    scopeName === "Terminating" ||
    scopeName === "NotTerminating" ||
    scopeName === "BestEffort" ||
    scopeName === "NotBestEffort"
  );
};

const onScopeNameChange = scopeRow => {
  if (isOperatorOnlyExist(scopeRow.scopeName)) {
    scopeRow.operator = "Exists";
  }
};

const unitSuffixDesc = row => {
  if (row.key?.indexOf(".memory") !== -1) {
    return "Mi";
  } else if (row.key?.indexOf(".cpu") !== -1) {
    return "mCpu";
  } else if (row.key?.indexOf(".storage") !== -1) {
    return "Gi";
  } else {
    return "none";
  }
};

const reloadEditData = (quota: ResourceQuotaSpec) => {
  hards.value = [];
  for (const key in Object.keys(quota.hard ?? {})) {
    if (Object.prototype.hasOwnProperty.call(quota.hard, key)) {
      if (key.indexOf(".cpu") !== -1) {
        hards.value.push({
          key: key,
          value: cpuUnitConvert(quota.hard[key])
        });
      } else if (
        key.indexOf(".memory") !== -1 ||
        key.indexOf(".storage") !== -1
      ) {
        hards.value.push({
          key: key,
          value: memoryUnitConvert(quota.hard[key])
        });
      } else {
        hards.value.push({
          key: key,
          value: quota.hard[key]
        });
      }
    }
  }
};

watch(
  () => props.resourceQuotaObj,
  newVal => {
    if (!newVal) return;
    reloadEditData(newVal);
  }
);
</script>

<style scoped></style>
